package com.github.facadefs.util;

/**
 * TODO DOC ME!.
 *
 * @author vacoor
 * @since 20240522
 */
public abstract class Paths {
    public static final String ROOT = "/";
    public static final String PATH_SEPARATOR = "/";
    private static final String CURRENT_DIR_NAME = ".";
    private static final String CURRENT_DIR = CURRENT_DIR_NAME + PATH_SEPARATOR;
    private static final String PARENT_DIR_NAME = "..";
    private static final String PARENT_DIR = PARENT_DIR_NAME + PATH_SEPARATOR;

    private Paths() {
    }

    public static boolean isCurrentDirName(final String name) {
        return CURRENT_DIR_NAME.equals(name);
    }

    public static boolean isParentDirName(final String name) {
        return PARENT_DIR_NAME.equals(name);
    }

    public static String toAbsolutePath(final String chroot, final String udfPath) {
        final String normalizedUdfPath = Path.normalize(udfPath);
        if (normalizedUdfPath.startsWith(PARENT_DIR)) {
            throw new IllegalArgumentException("Illegal path argument: " + udfPath);
        }

        final Path p = Path.get(udfPath);
        if (null == chroot) {
            return p.isAbsolute() ? p.getPath() : Path.get(PATH_SEPARATOR, p).getPath();
        }
        final Path chrootPath = Path.get(chroot);
        return p.startsWith(chroot) ? p.getPath() : chrootPath.resolve(p).getPath();
    }

    public static String toRelativePath(final String chroot, final String udfPath) {
        if (null == chroot) {
            return udfPath;
        }
        final String relativePath = Path.get(udfPath).relativize(chroot);
        return (CURRENT_DIR.equals(relativePath) || CURRENT_DIR_NAME.equals(relativePath))
                ? PATH_SEPARATOR : relativePath;
    }

}
